package com.shuqi.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.shuqi.activity.viewport.BottomDialog;
import com.shuqi.activity.viewport.CommonTitle;
import com.shuqi.common.Config;
import com.shuqi.common.FunctionsSwitch;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.SharedPreferenceUtil;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.R;
import com.shuqi.database.dao.impl.BookCataLogDao;
import com.shuqi.model.bean.StandbyServerInfo;
import com.shuqi.model.manager.DownLoadBookManager;
import com.shuqi.model.net.UrlManager;
import com.shuqi.service.CheckMarksUpdateService;
import com.shuqi.service.CheckPushMessageService;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

/**
 * 软件设置
 * 
 * @author linyuren
 * 
 */
public class SoftwareSettingActivity extends ActivityBase implements OnClickListener,
        OnCheckedChangeListener {

    private BottomDialog dialogMore = null;
    private TextView useing_which_server;
    private String serverName = "";// 显示server的名称
    private CommonTitle mTitle;
    private ToggleButton notice_bar_on_or_off/*, app_first_on_or_off*/;

    /** 缓存SharedPreferences中读取备选列表 */
    private List<StandbyServerInfo> infos = new ArrayList<StandbyServerInfo>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.act_software_setting);
        this.activityLogicForward();
    }

    @Override
    public void activityLogicForward() {
        mTitle = (CommonTitle) findViewById(R.id.title);
        mTitle.setLeftClickListener(this);
        this.useing_which_server = (TextView) this.findViewById(R.id.useing_which_server);
     
        this.notice_bar_on_or_off = (ToggleButton) this.findViewById(R.id.notice_bar_onoroff);
        this.notice_bar_on_or_off.setChecked(FunctionsSwitch.isNotificationOpen(getApplicationContext()));
        this.notice_bar_on_or_off.setOnCheckedChangeListener(this);// 添加监听事件

//        this.app_first_on_or_off = (ToggleButton) this.findViewById(R.id.app_first_on_or_off);
//        this.app_first_on_or_off.setChecked(FunctionsSwitch.isFirstOpenShelf(getApplicationContext()));
//        this.app_first_on_or_off.setOnCheckedChangeListener(this);// 添加监听事件

        this.findViewById(R.id.clean_cache).setOnClickListener(this);
        this.findViewById(R.id.alternative_server).setOnClickListener(this);
        this.initShowCurrentServer();

        this.initAllServer();
    }

    @Override
    public void activityInitData() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left:
                ActivityManager.getInstance().finishActivity(this);
                break;
            case R.id.alternative_server:
                this.showBottomDialog();
                break;
            case R.id.clean_cache:
                this.clearCache();
                StatisticsUtils.onEvent(this, StatisticsEventID.ACCOUNT_CLEAR_CACHE);
                break;
            case R.id.view_dia_but_sure:
                this.chooseServer();
                this.dialogMore.dismiss();
                break;
            case R.id.view_dia_but_selmobile_checkbox:
                this.serverName = "正用移动线路";
                this.chooseCheckbox();
                break;
            case R.id.view_dia_but_selunicom1_checkbox:
                this.serverName = "正用联通线路1";
                this.chooseCheckbox();
                break;
            case R.id.view_dia_but_selunicom2_checkbox:
                this.serverName = "正用联通线路2";
                this.chooseCheckbox();
                break;
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        switch (buttonView.getId()) {
            case R.id.notice_bar_onoroff:
                if (isChecked) {
                    FunctionsSwitch.openNotification(getApplicationContext());
                    CheckMarksUpdateService.startCheckBookMarksUpdate(getApplicationContext());
                    CheckPushMessageService.startCheckPushMessageUpdate(getApplicationContext());
                } else {
                    FunctionsSwitch.closeNotification(getApplicationContext());
                    CheckPushMessageService.cancelCheckPushMessageUpdate(getApplicationContext());
                    
                }
                StatisticsUtils.onEvent(this, StatisticsEventID.ACCOUNT_NOTIFICATIONBAR_UPDATE);
                break;
//            case R.id.app_first_on_or_off:
//                if(isChecked){
//                    FunctionsSwitch.openFirstOpenShelf(getApplicationContext());
//                }else{
//                    FunctionsSwitch.closeFirstOpenShelf(getApplicationContext());
//                }
//                StatisticsUtils.onEvent(this, StatisticsEventID.ACCOUNT_FIRSTSCREEN_INTOSHELF);
//                break;
        }
    }

    @Override
    public void onResume() {
        initShowCurrentServer();
        super.onResume();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /** 显示底部弹出框 */
    private void showBottomDialog() {
        if (this.dialogMore == null) {
            View viewv = View.inflate(this, R.layout.view_dialog_choose_server, null);
            this.dialogMore = new BottomDialog(this, viewv);
            this.initBookShelfMoreDialog(viewv);
            viewv.setOnClickListener(this);
        }
        this.dialogMore.show();
    }

    private CheckBox selmobile_checkbox;
    private CheckBox selunicom1_checkbox;
    private CheckBox selunicom2_checkbox;

    /**
     * 初始化删除对话框
     */
    private void initBookShelfMoreDialog(View view) {
        selmobile_checkbox = (CheckBox) view.findViewById(R.id.view_dia_but_selmobile_checkbox);
        selunicom1_checkbox = (CheckBox) view.findViewById(R.id.view_dia_but_selunicom1_checkbox);
        selunicom2_checkbox = (CheckBox) view.findViewById(R.id.view_dia_but_selunicom2_checkbox);

        if (this.useing_which_server.getText().toString().equals("正用移动线路")) {
            selmobile_checkbox.setChecked(true);
        } else if (this.useing_which_server.getText().toString().equals("正用联通线路1")) {
            selunicom1_checkbox.setChecked(true);
        } else if (this.useing_which_server.getText().toString().equals("正用联通线路2")) {
            selunicom2_checkbox.setChecked(true);
        }

        selmobile_checkbox.setOnClickListener(this);
        selunicom1_checkbox.setOnClickListener(this);
        selunicom2_checkbox.setOnClickListener(this);

        view.findViewById(R.id.view_dia_but_sure).setOnClickListener(this);
    }

    /** 切换不同的服务器线路选中对应的checkbox */
    private void chooseCheckbox() {
        if (this.serverName.equals("正用移动线路")) {
            this.selmobile_checkbox.setChecked(true);
            this.selunicom1_checkbox.setChecked(false);
            this.selunicom2_checkbox.setChecked(false);
        } else if (this.serverName.equals("正用联通线路1")) {
            this.selmobile_checkbox.setChecked(false);
            this.selunicom1_checkbox.setChecked(true);
            this.selunicom2_checkbox.setChecked(false);
        } else if (this.serverName.equals("正用联通线路2")) {
            this.selmobile_checkbox.setChecked(false);
            this.selunicom1_checkbox.setChecked(false);
            this.selunicom2_checkbox.setChecked(true);
        }
    }

    /** 切换不同的服务器线路逻辑处理 */
    private void chooseServer() {
        this.useing_which_server.setText(this.serverName);
        SharedPreferences sp = getSharedPreferences(SharedPreferenceUtil.SP_NAME_SERVERS, MODE_PRIVATE);
        Editor ed = sp.edit();
        int index = 0;
        if (this.serverName.equals("正用移动线路")) {
            index = 0;
        } else if (this.serverName.equals("正用联通线路1")) {
            index = 1;
        } else if (this.serverName.equals("正用联通线路2")) {
            index = 2;
        }
        // 首次连网
        ed.putString("standby_server", infos.get(index).getServer());
        ed.putString("standby_server1", infos.get(index).getServer1());
        ed.putString("standby_server2", infos.get(index).getServer2());
        ed.putString("standby_server3", infos.get(index).getServer3());
        // 重试1
        ed.putString("standby_server1_0", infos.get(index).getServer1_0());
        ed.putString("standby_server1_1", infos.get(index).getServer1_1());
        ed.putString("standby_server1_2", infos.get(index).getServer1_2());
        ed.putString("standby_server1_3", infos.get(index).getServer1_3());
        // 重试2
        ed.putString("standby_server2_0", infos.get(index).getServer2_0());
        ed.putString("standby_server2_1", infos.get(index).getServer2_1());
        ed.putString("standby_server2_2", infos.get(index).getServer2_2());
        ed.putString("standby_server2_3", infos.get(index).getServer2_3());

        ed.putInt("server_index", index);// 保存当前选择的服务器序列号
        ed.commit();

    }

    /** 清理缓存 */
    private void clearCache() {
        final ProgressDialog pdialog = new ProgressDialog(this);
        pdialog.setMessage("稍等,正清除...");
        pdialog.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    
                    String[] mCaches ={Config.DEFAULT_PATH_COVER,Config.DEFAULT_PATH_BOOKCOVER }; 
                    List<File> list = new ArrayList<File>();
                    for (int i = 0; i < mCaches.length; i++) {
                        list.add(new File(mCaches[i]));
                    }
                    list.add(getCacheDir());
                    
                    for (File cacheFile : list) {
                        if (cacheFile != null && cacheFile.exists() && cacheFile.isDirectory()) {
                            delFolder(cacheFile.getAbsolutePath());
                            cacheFile.delete();
                        }
                    }
                    SoftwareSettingActivity.this.deleteDatabase("webview.db");
                    SoftwareSettingActivity.this.deleteDatabase("webviewCache.db");
                    
                    SharedPreferences sp=getSharedPreferences("tempcatalog", MODE_PRIVATE);  
                    Map map=sp.getAll();
                    Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
                    while (it.hasNext()) {
                     Map.Entry<String, String> entry = it.next();
                     String[] key=entry.getKey().split("##");
                     String cid=entry.getValue();
                     File dir = null;
                     //bookId##userId##sourceId
                     if(key.length<3){
                       //TODO 关闭软件时 清除缓存目录对应的表
                         BookCataLogDao.getInstance().deleteBookCatalogByBookId(key[0], null, key[1]);
                       //TODO 关闭软件时 删除wifi下缓存的文件
                         dir = new File(Config.DEFAULT_SHUQI_CHAPTER_CACHE_PATH + key[1] + "/" + key[0] + "/");
                     }else{
                         BookCataLogDao.getInstance().deleteBookCatalogByBookId(key[0], key[2], key[1]);
                       //TODO 关闭软件时 删除wifi下缓存的文件
                         dir =
                                 new File(Config.DEFAULT_YISOU_CHAPTER_CACHE_PATH + key[1] + "/" + key[2] + "/"
                                         + key[0] + "/");
                     }
                   
                     
                     if (!dir.exists()) {
                         dir.mkdirs();
                     }
                     File file = new File(dir, cid + DownLoadBookManager.CHAPTER_FILE_SUFFIX);
                     if (file.exists()) {
                         try {
                             if (file.isDirectory()) {
                                 Util.forceDelDir(file);
                             } else {
                                 file.delete();
                             }
                         } catch (Exception e) {
                             e.printStackTrace();
                         }
                     }
                    }
                    
                  
                } catch (Exception e) {
                    Log.e("clearCache", "clear failed");
                } finally {
                    if (pdialog != null && pdialog.isShowing()) {
                        try {
                            pdialog.dismiss();
                            showMsg("清除缓存成功");
                        } catch (Exception e2) {
                        }
                    }
                }
            }
        }).start();
    }

    /**
     * 删除指定文件夹下所有文件
     * 
     * @param path文件夹完整绝对路径
     */
    private void delFolder(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        if (!file.isDirectory()) {
            return;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delFolder(path + "/" + tempList[i]);// 先删除文件夹里面的文件
                temp.delete();// 再删除空文件夹
            }
        }
        Log4an.i("clearCache", "clear success: "+path);
    }

    /** 更新显示被选服务器当前的状态 */
    private void initShowCurrentServer() {
        SharedPreferences sp = getSharedPreferences(SharedPreferenceUtil.SP_NAME_SERVERS, MODE_PRIVATE);
        int server_index = sp.getInt("server_index", -1);// 如果没有选择过服务器列表，使用默认移动线路
        if (server_index == 0) {
            useing_which_server.setText("正用移动线路");
        } else if (server_index == 1) {
            useing_which_server.setText("正用联通线路1");
        } else if (server_index == 2) {
            useing_which_server.setText("正用联通线路2");
        } else {
            SharedPreferences sp_config = getSharedPreferences(SharedPreferenceUtil.SP_NAME_SERVERS, MODE_PRIVATE);
            SharedPreferences sp_slist = getSharedPreferences("serverlist", MODE_PRIVATE);
            String ip0 = sp_config.getString("standby_server", UrlManager.SERVER_IPS[0][0][0]);
            String ip1 = sp_config.getString("standby_server1_0", UrlManager.SERVER_IPS[0][1][0]);
            String ip2 = sp_config.getString("standby_server2_0", UrlManager.SERVER_IPS[0][2][0]);

            if (ip0.equals(sp_slist.getString("000", UrlManager.SERVER_IPS[0][0][0]))
                    && ip1.equals(sp_slist.getString("010", UrlManager.SERVER_IPS[0][1][0]))
                    && ip2.equals(sp_slist.getString("020", UrlManager.SERVER_IPS[0][2][0]))) {
                useing_which_server.setText("正用移动线路");
            } else if (ip0.equals(sp_slist.getString("100", UrlManager.SERVER_IPS[1][0][0]))
                    && ip1.equals(sp_slist.getString("110", UrlManager.SERVER_IPS[1][1][0]))
                    && ip2.equals(sp_slist.getString("120", UrlManager.SERVER_IPS[1][2][0]))) {
                useing_which_server.setText("正用联通线路1");
            } else if (ip0.equals(sp_slist.getString("200", UrlManager.SERVER_IPS[2][0][0]))
                    && ip1.equals(sp_slist.getString("210", UrlManager.SERVER_IPS[2][1][0]))
                    && ip2.equals(sp_slist.getString("220", UrlManager.SERVER_IPS[2][2][0]))) {
                useing_which_server.setText("正用联通线路2");
            } else {
                useing_which_server.setText("正用移动线路");
            }
        }
    }

    /** 更新显示被选服务器当前的状态 */
    private void initAllServer() {
        // 从SharedPreferences中读取备选列表
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            StandbyServerInfo info = new StandbyServerInfo();
            SharedPreferences sp = getSharedPreferences("serverlist", MODE_PRIVATE);
            // 首次连网
            String server = sp.getString(i + "00", null);
            if (TextUtils.isEmpty(server)) {
                if (i < 3) {
                    server = UrlManager.SERVER_IPS[i][0][0];
                } else {
                    break;
                }
            }
            info.setServer(server.trim());

            String server1 = sp.getString(i + "01", null);
            if (TextUtils.isEmpty(server1)) {
                if (i < 3) {
                    server1 = UrlManager.SERVER_IPS[i][0][1];
                } else {
                    break;
                }
            }
            info.setServer1(server1.trim());

            String server2 = sp.getString(i + "02", null);
            if (TextUtils.isEmpty(server2)) {
                if (i < 3) {
                    server2 = UrlManager.SERVER_IPS[i][0][2];
                } else {
                    break;
                }
            }
            info.setServer2(server2.trim());

            String server3 = sp.getString(i + "03", null);
            if (TextUtils.isEmpty(server3)) {
                if (i < 3) {
                    server3 = UrlManager.SERVER_IPS[i][0][3];
                } else {
                    break;
                }
            }
            info.setServer3(server3.trim());
            // 重试1
            String server1_0 = sp.getString(i + "10", null);
            if (TextUtils.isEmpty(server1_0)) {
                if (i < 3) {
                    server1_0 = UrlManager.SERVER_IPS[i][1][0];
                } else {
                    break;
                }
            }
            info.setServer1_0(server1_0.trim());
            String server1_1 = sp.getString(i + "11", null);
            if (TextUtils.isEmpty(server1_1)) {
                if (i < 3) {
                    server1_1 = UrlManager.SERVER_IPS[i][1][1];
                } else {
                    break;
                }
            }
            info.setServer1_1(server1_1.trim());
            String server1_2 = sp.getString(i + "12", null);
            if (TextUtils.isEmpty(server1_2)) {
                if (i < 3) {
                    server1_2 = UrlManager.SERVER_IPS[i][1][2];
                } else {
                    break;
                }
            }
            info.setServer1_2(server1_2.trim());

            String server1_3 = sp.getString(i + "13", null);
            if (TextUtils.isEmpty(server1_3)) {
                if (i < 3) {
                    server1_3 = UrlManager.SERVER_IPS[i][1][3];
                } else {
                    break;
                }
            }
            info.setServer1_3(server1_3.trim());
            // 重试2
            String server2_0 = sp.getString(i + "20", null);
            if (TextUtils.isEmpty(server2_0)) {
                if (i < 3) {
                    server2_0 = UrlManager.SERVER_IPS[i][2][0];
                } else {
                    break;
                }
            }
            info.setServer2_0(server2_0.trim());
            String server2_1 = sp.getString(i + "21", null);
            if (TextUtils.isEmpty(server2_1)) {
                if (i < 3) {
                    server2_1 = UrlManager.SERVER_IPS[i][2][1];
                } else {
                    break;
                }
            }
            info.setServer2_1(server2_1.trim());
            String server2_2 = sp.getString(i + "22", null);
            if (TextUtils.isEmpty(server2_2)) {
                if (i < 3) {
                    server2_2 = UrlManager.SERVER_IPS[i][2][2];
                } else {
                    break;
                }
            }
            info.setServer2_2(server2_2.trim());
            String server2_3 = sp.getString(i + "23", null);
            if (TextUtils.isEmpty(server2_3)) {
                if (i < 3) {
                    server2_3 = UrlManager.SERVER_IPS[i][2][3];
                } else {
                    break;
                }
            }
            info.setServer2_3(server2_3.trim());
            info.setItemname("备用服务器" + i);
            infos.add(info);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            ActivityManager.getInstance().finishActivity(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
